package com.example.cglib.proxy;

import lombok.Data;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibMain {

    @Data
    static class User {
        private String name = "halo";
        private Integer age = 1;
    }

    static class UserCallBack implements MethodInterceptor {

        private Object target;

        public UserCallBack(User user) {
            this.target = user;
        }

        @Override
        public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            if ("toString".equals(method.getName())) {
                String s = (String) methodProxy.invokeSuper(object, args);
                return s + "cglib proxy";
            }

            if ("hashCode".equals(method.getName())) {
                return method.invoke(target, args);
            }
            // 简单描述: 如果调用 就写 invokeSuper, 否则需要拿到实例对象后 调用 invoke 方法
            return methodProxy.invokeSuper(object, args);
        }
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(User.class);
        enhancer.setCallback(new UserCallBack(new User()));
        Object o = enhancer.create();
        System.out.println(o.toString());
        System.out.println(o.hashCode());
    }
}
